package com.southminority.ethnic.controller.admin.excel;

import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.pojo.MinorityLanguageCulture;
import com.southminority.ethnic.pojo.MinorityLanguageSentence;
import com.southminority.ethnic.pojo.MinorityLanguageSpeech;
import com.southminority.ethnic.mapper.language.MinorityLanguageCultureMapper;
import com.southminority.ethnic.mapper.language.MinorityLanguageSentenceMapper;
import com.southminority.ethnic.mapper.language.MinorityLanguageSpeechMapper;
import com.southminority.ethnic.until.ExcelUntil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
@Tag(name = "excel-语言数据库", description = "语言数据库导入导出（三类）")
@RestController
@RequestMapping("/admin/language-excel")
@CrossOrigin
public class LanguageExcelController {
    @Autowired private MinorityLanguageCultureMapper cultureMapper;
    @Autowired private MinorityLanguageSentenceMapper sentenceMapper;
    @Autowired private MinorityLanguageSpeechMapper speechMapper;

    // ========== 口传文化 ==========
    @GetMapping("/culture/output")
    @Operation(summary = "导出口传文化", description = "导出口传文化")
    public ResponseEntity<byte[]> outputCulture() {
        try {
            List<MinorityLanguageCulture> dataList = cultureMapper.selectList(null);
            byte[] excelBytes = ExcelUntil.exportExcel(dataList);
            return download(excelBytes, "language_culture_output");
        } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);} }

    @GetMapping("/culture/mb-input")
    @Operation(summary = "模板-口传文化", description = "模板-口传文化")
    public ResponseEntity<byte[]> tplCulture() { try { return download(ExcelUntil.mbExcel(MinorityLanguageCulture.class), "language_culture_input"); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);} }

    @PostMapping("/culture/input")
    @Operation(summary = "导入口传文化", description = "导入口传文化")
    public R<String> importCulture(@RequestParam("file") MultipartFile file) { try { List<MinorityLanguageCulture> list = ExcelUntil.importExcel(file, MinorityLanguageCulture.class); for (var it : list) { if (it.getId()==null) cultureMapper.insert(it); else cultureMapper.updateById(it);} return R.ok("导入成功，共"+list.size()+"条数据"); } catch (Exception e) { e.printStackTrace(); return R.fail("导入失败："+e.getMessage()); } }

    // ========== 句子 ==========
    @GetMapping("/sentence/output")
    @Operation(summary = "导出句子", description = "导出句子")
    public ResponseEntity<byte[]> outputSentence() { try { var dataList = sentenceMapper.selectList(null); return download(ExcelUntil.exportExcel(dataList), "language_sentence_output"); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);} }

    @GetMapping("/sentence/mb-input")
    @Operation(summary = "模板-句子", description = "模板-句子")
    public ResponseEntity<byte[]> tplSentence() { try { return download(ExcelUntil.mbExcel(MinorityLanguageSentence.class), "language_sentence_input"); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);} }

    @PostMapping("/sentence/input")
    @Operation(summary = "导入句子", description = "导入句子")
    public R<String> importSentence(@RequestParam("file") MultipartFile file) { try { var list = ExcelUntil.importExcel(file, MinorityLanguageSentence.class); for (var it : list) { if (it.getId()==null) sentenceMapper.insert(it); else sentenceMapper.updateById(it);} return R.ok("导入成功，共"+list.size()+"条数据"); } catch (Exception e) { e.printStackTrace(); return R.fail("导入失败："+e.getMessage()); } }

    // ========== 词汇 ==========
    @GetMapping("/speech/output")
    @Operation(summary = "导出词汇", description = "导出词汇")
    public ResponseEntity<byte[]> outputSpeech() { try { var dataList = speechMapper.selectList(null); return download(ExcelUntil.exportExcel(dataList), "language_speech_output"); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);} }

    @GetMapping("/speech/mb-input")
    @Operation(summary = "模板-词汇", description = "模板-词汇")
    public ResponseEntity<byte[]> tplSpeech() { try { return download(ExcelUntil.mbExcel(MinorityLanguageSpeech.class), "language_speech_input"); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);} }

    @PostMapping("/speech/input")
    @Operation(summary = "导入词汇", description = "导入词汇")
    public R<String> importSpeech(@RequestParam("file") MultipartFile file) { try { var list = ExcelUntil.importExcel(file, MinorityLanguageSpeech.class); for (var it : list) { if (it.getId()==null) speechMapper.insert(it); else speechMapper.updateById(it);} return R.ok("导入成功，共"+list.size()+"条数据"); } catch (Exception e) { e.printStackTrace(); return R.fail("导入失败："+e.getMessage()); } }

    private ResponseEntity<byte[]> download(byte[] bytes, String fileName) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String encodedFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx";
        headers.setContentDispositionFormData("attachment", encodedFileName);
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }
}


